package com.ls.controller;

import com.alibaba.fastjson.JSON;
import com.ls.pojo.Supplier;
import com.ls.pojo.SysUser;
import com.ls.service.supplier.SupplierService;
import com.ls.utils.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/sys/supplier/")
public class SupplierController {
    private Logger logger = Logger.getLogger(SupplierController.class);

    @Resource
    private SupplierService supplierService;

    @RequestMapping(value = "/list")
    public String list(@RequestParam(required = false) String querySupCode, @RequestParam(required = false) String querySupName,
                       @RequestParam(defaultValue = "1") Integer pageIndex, Model model) throws Exception {
        List<Supplier> supplierList = null;
        int pageSize = 5;
        int totalCount = supplierService.getCount(querySupName, querySupCode);

        PageSupport page = new PageSupport();
        page.setCurrentPageNo(pageIndex);
        page.setPageSize(pageSize);
        page.setTotalCount(totalCount);

        int totalPageCount = page.getTotalPageCount();

        if (pageIndex > totalPageCount) {
            pageIndex = totalPageCount;
        }

        supplierList = supplierService.getList(querySupName, querySupCode, pageIndex, pageSize);

        model.addAttribute("supplierList", supplierList);
        model.addAttribute("querySupCode", querySupCode);
        model.addAttribute("querySupName", querySupName);

        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", pageIndex);

        return "supplier/list";
    }

    @GetMapping(value = "/toAdd")
    public String toAdd() {
        return "supplier/add";
    }

    @PostMapping(value = "/add")
    public String add(@RequestParam(required = false) MultipartFile[] attachs, Supplier supplier,
                      HttpSession session, HttpServletRequest request) {
        String companyLicPicPath = null;
        String orgCodePicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        this.logger.info("uploadFile path ============== > " + path);

        for(int i = 0; i < attachs.length; ++i) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadOcError";
                }

                String oldFileName = attach.getOriginalFilename();
                String prefix = FilenameUtils.getExtension(oldFileName);
                int filesize = 500000;
                if (attach.getSize() > (long) filesize) {
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
                    flag = false;
                } else if (!prefix.equalsIgnoreCase("jpg") && !prefix.equalsIgnoreCase("png") && !prefix.equalsIgnoreCase("jpeg") && !prefix.equalsIgnoreCase("pneg")) {
                    request.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                } else {
                    String fileName = System.currentTimeMillis() + (long) RandomUtils.nextInt(1000000) + "_Personal.jpg";
                    this.logger.debug("new fileName======== " + attach.getName());
                    File targetFile = new File(path, fileName);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }

                    try {
                        attach.transferTo(targetFile);
                    } catch (Exception var19) {
                        var19.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败！");
                        flag = false;
                    }

                    if (i == 0) {
                        companyLicPicPath = path + File.separator + fileName;
                    } else if (i == 1) {
                        orgCodePicPath = path + File.separator + fileName;
                    }

                    this.logger.debug("companyLicPicPath: " + companyLicPicPath);
                    this.logger.debug("orgCodePicPath: " + orgCodePicPath);
                }
            }
        }

        return "supplier/add";
    }

    @ResponseBody
    @DeleteMapping(value = "/del/{id}")
    public String del(@PathVariable Integer id) {
        HashMap resultMap = new HashMap();
        boolean flag = false;

        try {
            flag = supplierService.deleteById(id);

            if (flag) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JSON.toJSONString(resultMap);
    }

    @GetMapping(value = "/view/{id}")
    public String view(@PathVariable Integer id, HttpServletRequest request, Model model) throws Exception {
        Supplier supplier = supplierService.getById(id);
        String[] paths;

        if (supplier.getCompanyLicPicPath() != null && !supplier.getCompanyLicPicPath().equals("")) {
            paths = supplier.getCompanyLicPicPath().split("\\\\" + File.separator);
            supplier.setCompanyLicPicPath(request.getContextPath() + "/statics/uploadfiles/" + paths[paths.length - 1]);
        }

        if (supplier.getOrgCodePicPath() != null && !supplier.getOrgCodePicPath().equals("")) {
            paths = supplier.getOrgCodePicPath().split("\\\\" + File.separator);
            supplier.setOrgCodePicPath(request.getContextPath() + "/statics/uploadfiles/" + paths[paths.length - 1]);
        }

        model.addAttribute(supplier);

        return "supplier/view";
    }

    @GetMapping(value = "/toUpdate/{id}")
    public String toUpdate(@PathVariable Integer id, Model model) throws Exception {
        Supplier supplier = supplierService.getById(id);
        model.addAttribute(supplier);
        return "supplier/update";
    }

    @PostMapping(value = "/update")
    public String update(Supplier supplier, HttpSession session) throws Exception {
        supplier.setCreatedUserId(((SysUser)session.getAttribute("userSession")).getId());
        return supplierService.update(supplier) ? "redirect:/sys/supplier/list" : "supplier/update";
    }

    @ResponseBody
    @GetMapping(value = "/simpleList")
    public List<Supplier> simpleList() {
        List supplierList = null;

        try {
            supplierList = supplierService.getList();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return supplierList;
    }
}